package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    /**
     * 生成文章静态页面
     */

    @Autowired
    Configuration configuration;

    @Autowired
    AuthorMapper authorMapper;

    @Resource(name = "minIOFileStorageService")
    FileStorageService minIOFileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;


    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {

        try {
            //获取模板
            Template template = configuration.getTemplate("article.ftl");

            //准备数据
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            Integer userId = apAuthor.getUserId();
            Map dataModel = new HashMap();
            dataModel.put("authorApUserId",userId); //作者对应的用户id
            dataModel.put("article",apArticle); //作者对应的用户id
            dataModel.put("content", JSONArray.parseArray(content,Map.class));

            StringWriter writer = new StringWriter();

            template.process(dataModel,writer);
            String contentHtml = writer.toString();

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentHtml.getBytes());
            //将数据上传到minio
            String store = minIOFileStorageService.store(prefix, apArticle.getId() + ".html", "text/html",
                    byteArrayInputStream);

            //将minio中的静态页的路径设置到aticle表中的static_yrl属性上
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
            log.error("生成静态页失败");
        }



    }

}